<template>
	<div class="credential-detail-container">
		<el-dialog title="凭证详情" v-model="state.dialog.isShowDialog" width="700px" @close="closeDialog">
			<div class="credential-detail-content" v-loading="state.loading">
				<el-descriptions :column="2" border>
					<el-descriptions-item label="凭证ID">
						<span>{{ state.credentialDetail.credentialId }}</span>
						<el-button
							size="small"
							text
							type="primary"
							@click="copyToClipboard(state.credentialDetail.credentialId)"
							class="ml5"
						>
							<el-icon><ele-CopyDocument /></el-icon>
						</el-button>
					</el-descriptions-item>
					<el-descriptions-item label="凭证类型">
						<el-tag :type="getCredentialTypeTag(state.credentialDetail.type)">
							{{ getCredentialTypeName(state.credentialDetail.type) }}
						</el-tag>
					</el-descriptions-item>
					<el-descriptions-item label="作用域">
						<el-tag :type="state.credentialDetail.scope === 'GLOBAL' ? 'success' : 'info'">
							{{ state.credentialDetail.scope }}
						</el-tag>
					</el-descriptions-item>
					<el-descriptions-item label="使用次数">
						{{ state.credentialDetail.usageCount || 0 }}
					</el-descriptions-item>
					<el-descriptions-item label="创建人">
						{{ state.credentialDetail.creator || '-' }}
					</el-descriptions-item>
					<el-descriptions-item label="修改人">
						{{ state.credentialDetail.modifier || '-' }}
					</el-descriptions-item>
					<el-descriptions-item label="创建时间">
						{{ state.credentialDetail.createdTime || '-' }}
					</el-descriptions-item>
					<el-descriptions-item label="更新时间">
						{{ state.credentialDetail.updatedTime || '-' }}
					</el-descriptions-item>
					<el-descriptions-item label="描述" :span="2">
						{{ state.credentialDetail.description || '-' }}
					</el-descriptions-item>
				</el-descriptions>

				<!-- 敏感信息展示区域 -->
				<div class="sensitive-info-section mt20" v-if="hasSensitiveInfo">
					<el-divider content-position="left">
						<span class="sensitive-info-title">
							<el-icon><ele-Lock /></el-icon>
							敏感信息
						</span>
					</el-divider>

					<!-- 用户名密码类型 -->
					<template v-if="state.credentialDetail.type === 'usernamePassword'">
						<el-descriptions :column="1" border>
							<el-descriptions-item label="用户名">
								{{ state.credentialDetail.username || '-' }}
							</el-descriptions-item>
							<el-descriptions-item label="密码">
								<div class="sensitive-field">
									<span v-if="!state.showPassword">********</span>
									<span v-else>{{ state.sensitiveData.password || '-' }}</span>
									<el-button
										size="small"
										text
										type="primary"
										@click="togglePasswordVisibility"
										class="ml10"
									>
										<el-icon>
											<ele-View v-if="!state.showPassword" />
											<ele-Hide v-else />
										</el-icon>
									</el-button>
									<el-button
										v-if="state.showPassword && state.sensitiveData.password"
										size="small"
										text
										type="primary"
										@click="copyToClipboard(state.sensitiveData.password)"
									>
										<el-icon><ele-CopyDocument /></el-icon>
									</el-button>
								</div>
							</el-descriptions-item>
						</el-descriptions>
					</template>

					<!-- SSH密钥类型 -->
					<template v-if="state.credentialDetail.type === 'sshKey'">
						<el-descriptions :column="1" border>
							<el-descriptions-item label="用户名">
								{{ state.credentialDetail.username || '-' }}
							</el-descriptions-item>
							<el-descriptions-item label="密码短语">
								<div class="sensitive-field">
									<span v-if="!state.showPassphrase">{{ state.sensitiveData.passphrase ? '********' : '-' }}</span>
									<span v-else>{{ state.sensitiveData.passphrase || '-' }}</span>
									<el-button
										v-if="state.sensitiveData.passphrase"
										size="small"
										text
										type="primary"
										@click="state.showPassphrase = !state.showPassphrase"
										class="ml10"
									>
										<el-icon>
											<ele-View v-if="!state.showPassphrase" />
											<ele-Hide v-else />
										</el-icon>
									</el-button>
								</div>
							</el-descriptions-item>
							<el-descriptions-item label="私钥">
								<div class="sensitive-field">
									<div v-if="!state.showPrivateKey" class="private-key-masked">
										<span>{{ state.sensitiveData.privateKey ? '私钥已设置 (点击查看)' : '-' }}</span>
									</div>
									<pre v-else class="private-key-content">{{ state.sensitiveData.privateKey || '-' }}</pre>
									<div class="private-key-actions">
										<el-button
											v-if="state.sensitiveData.privateKey"
											size="small"
											text
											type="primary"
											@click="state.showPrivateKey = !state.showPrivateKey"
										>
											<el-icon>
												<ele-View v-if="!state.showPrivateKey" />
												<ele-Hide v-else />
											</el-icon>
											{{ state.showPrivateKey ? '隐藏' : '查看' }}
										</el-button>
										<el-button
											v-if="state.showPrivateKey && state.sensitiveData.privateKey"
											size="small"
											text
											type="primary"
											@click="copyToClipboard(state.sensitiveData.privateKey)"
										>
											<el-icon><ele-CopyDocument /></el-icon>
											复制
										</el-button>
									</div>
								</div>
							</el-descriptions-item>
						</el-descriptions>
					</template>

					<!-- 密钥文本类型 -->
					<template v-if="state.credentialDetail.type === 'secretText'">
						<el-descriptions :column="1" border>
							<el-descriptions-item label="密钥文本">
								<div class="sensitive-field">
									<div v-if="!state.showSecretText" class="secret-text-masked">
										<span>{{ state.sensitiveData.secretText ? '密钥文本已设置 (点击查看)' : '-' }}</span>
									</div>
									<pre v-else class="secret-text-content">{{ state.sensitiveData.secretText || '-' }}</pre>
									<div class="secret-text-actions">
										<el-button
											v-if="state.sensitiveData.secretText"
											size="small"
											text
											type="primary"
											@click="state.showSecretText = !state.showSecretText"
										>
											<el-icon>
												<ele-View v-if="!state.showSecretText" />
												<ele-Hide v-else />
											</el-icon>
											{{ state.showSecretText ? '隐藏' : '查看' }}
										</el-button>
										<el-button
											v-if="state.showSecretText && state.sensitiveData.secretText"
											size="small"
											text
											type="primary"
											@click="copyToClipboard(state.sensitiveData.secretText)"
										>
											<el-icon><ele-CopyDocument /></el-icon>
											复制
										</el-button>
									</div>
								</div>
							</el-descriptions-item>
						</el-descriptions>
					</template>

					<!-- 证书类型 -->
					<template v-if="state.credentialDetail.type === 'certificate'">
						<el-descriptions :column="1" border>
							<el-descriptions-item label="证书内容">
								<div class="sensitive-field">
									<div v-if="!state.showCertificate" class="certificate-masked">
										<span>{{ state.sensitiveData.certificate ? '证书已设置 (点击查看)' : '-' }}</span>
									</div>
									<pre v-else class="certificate-content">{{ state.sensitiveData.certificate || '-' }}</pre>
									<div class="certificate-actions">
										<el-button
											v-if="state.sensitiveData.certificate"
											size="small"
											text
											type="primary"
											@click="state.showCertificate = !state.showCertificate"
										>
											<el-icon>
												<ele-View v-if="!state.showCertificate" />
												<ele-Hide v-else />
											</el-icon>
											{{ state.showCertificate ? '隐藏' : '查看' }}
										</el-button>
										<el-button
											v-if="state.showCertificate && state.sensitiveData.certificate"
											size="small"
											text
											type="primary"
											@click="copyToClipboard(state.sensitiveData.certificate)"
										>
											<el-icon><ele-CopyDocument /></el-icon>
											复制
										</el-button>
									</div>
								</div>
							</el-descriptions-item>
						</el-descriptions>
					</template>
				</div>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="closeDialog" size="default">关 闭</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="credentialDetail">
import { reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { credentialApi, type CredentialItem } from '/@/api/jenkins/credential';

// 定义变量内容
const state = reactive<{
	credentialDetail: Partial<CredentialItem>;
	sensitiveData: {
		password?: string;
		privateKey?: string;
		passphrase?: string;
		secretText?: string;
		certificate?: string;
	};
	dialog: {
		isShowDialog: boolean;
	};
	loading: boolean;
	showPassword: boolean;
	showPrivateKey: boolean;
	showPassphrase: boolean;
	showSecretText: boolean;
	showCertificate: boolean;
}>({
	credentialDetail: {},
	sensitiveData: {},
	dialog: {
		isShowDialog: false,
	},
	loading: false,
	showPassword: false,
	showPrivateKey: false,
	showPassphrase: false,
	showSecretText: false,
	showCertificate: false,
});

// 是否有敏感信息
const hasSensitiveInfo = computed(() => {
	return ['usernamePassword', 'sshKey', 'secretText', 'certificate'].includes(state.credentialDetail.type || '');
});

// 打开弹窗
const openDialog = (row: CredentialItem) => {
	resetState();
	state.credentialDetail = { ...row };
	state.dialog.isShowDialog = true;
	// 获取敏感信息
	loadSensitiveData(row.id);
};

// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
	resetState();
};

// 重置状态
const resetState = () => {
	state.credentialDetail = {};
	state.sensitiveData = {};
	state.loading = false;
	state.showPassword = false;
	state.showPrivateKey = false;
	state.showPassphrase = false;
	state.showSecretText = false;
	state.showCertificate = false;
};

// 加载敏感数据
const loadSensitiveData = (id: number) => {
	state.loading = true;
	credentialApi()
		.getCredentialDetail({ id })
		.then((res) => {
			state.sensitiveData = res.data || {};
		})
		.catch(() => {
			// 错误处理由拦截器统一处理
		})
		.finally(() => {
			state.loading = false;
		});
};

// 切换密码可见性
const togglePasswordVisibility = () => {
	state.showPassword = !state.showPassword;
};

// 复制到剪贴板
const copyToClipboard = async (text: string) => {
	try {
		await navigator.clipboard.writeText(text);
		ElMessage.success('复制成功');
	} catch (err) {
		ElMessage.error('复制失败');
	}
};

// 获取凭证类型名称
const getCredentialTypeName = (type: string) => {
	const typeMap: Record<string, string> = {
		usernamePassword: '用户名密码',
		sshKey: 'SSH密钥',
		secretText: '密钥文本',
		certificate: '证书',
	};
	return typeMap[type] || type;
};

// 获取凭证类型标签颜色
const getCredentialTypeTag = (type: string) => {
	const tagMap: Record<string, string> = {
		usernamePassword: 'primary',
		sshKey: 'success',
		secretText: 'warning',
		certificate: 'info',
	};
	return tagMap[type] || '';
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
.credential-detail-container {
	.credential-detail-content {
		max-height: 70vh;
		overflow-y: auto;
	}

	.sensitive-info-section {
		.sensitive-info-title {
			display: flex;
			align-items: center;
			gap: 5px;
			color: #e6a23c;
			font-weight: 500;
		}
	}

	.sensitive-field {
		display: flex;
		align-items: center;
		gap: 10px;
		flex-wrap: wrap;

		.private-key-content,
		.secret-text-content,
		.certificate-content {
			background-color: #f5f7fa;
			border: 1px solid #dcdfe6;
			border-radius: 4px;
			padding: 12px;
			margin: 8px 0;
			font-family: 'Courier New', monospace;
			font-size: 12px;
			line-height: 1.4;
			max-height: 200px;
			overflow-y: auto;
			white-space: pre-wrap;
			word-break: break-all;
			width: 100%;
		}

		.private-key-masked,
		.secret-text-masked,
		.certificate-masked {
			color: #909399;
			font-style: italic;
		}

		.private-key-actions,
		.secret-text-actions,
		.certificate-actions {
			display: flex;
			gap: 8px;
			margin-top: 8px;
		}
	}
}
</style>